/**
 * @file 登录验证
 * @author liushuang(liushuang04@baijia.com)
 * @date 2019-11-14
 */

import React, {Component} from 'react';
import {Redirect} from 'react-router-dom';
import {connect} from 'react-redux';
import PropTypes from 'prop-types';
import {message} from 'antd';

import user from '~/model/user';
import {fetchUserInfo} from '~/service/user';

class Authorized extends Component {
    static propTypes = {
        dispatch: PropTypes.func.isRequired,
        children: PropTypes.node.isRequired,
        user: PropTypes.shape({
            displayName: PropTypes.string,
            selectRole: PropTypes.shape(),
            hasPermissions: PropTypes.array,
        }).isRequired,
    };

    componentDidMount() {
        // 获取用户信息
        const {user} = this.props;
        if (user.displayName === '') {
            fetchUserInfo()
                .then(res => {
                    const {data} = res;
                    const {displayName, hasRoles} = data;
                    const hasRolesFilter = hasRoles.filter(item =>
                        item.hasPermissions.findIndex(ele => ele.tag === 'portal_login') > -1);
                    if (hasRolesFilter && hasRolesFilter.length > 0) {
                        let roleId = hasRolesFilter[0].id;
                        if (window.localStorage.roleId) {
                            const selectRole = hasRolesFilter.filter(item =>
                                item.id.toString() === window.localStorage.roleId);
                            if (selectRole.length > 0) {
                                roleId = selectRole[0].id;
                            }
                        }

                        if (displayName && roleId) {
                            this.dispatchUserInfo({
                                ...data,
                                roleId
                            });
                            this.dispatchMenuList({
                                id: roleId,
                            });
                        }
                    }
                    else {
                        message.warn('该用户无角色');
                    }
                })
                .catch(() => {
                    message.error('获取用户信息失败，请重试！');
                });
        }
    }

    // 获取用户信息
    dispatchUserInfo(data) {
        const {dispatch} = this.props;
        dispatch(user.getUserInfo(data));
    }

    // 获取菜单list
    dispatchMenuList(params) {
        const {dispatch} = this.props;
        dispatch(user.getMenuList(params));
    }

    render() {
        const {children, user} = this.props;
        const {displayName, hasPermissions} = user;

        // 角色判断是否与权限, 根据权限的tag，判断是否包含 portal
        const index = hasPermissions.filter(item => item.tag.indexOf('portal') === 0);
        if (index.length === 0 && displayName && location.pathname !== '/noAuth') {
            // 无权限，跳转到noAuth;
            return <Redirect to={{pathname: '/noAuth'}} />;
        }

        return displayName
            // 初次render，还未获取到用户信息，此时避免重定向到login页
            ? (
                <div className="auth">
                    {children}
                </div>
            )
            : (
                null
            );
    }
}

export default connect(s => s)(Authorized);
